package com.xiangming.demo.service.imp;

import com.xiangming.demo.mapper.LogMapper;
import com.xiangming.demo.service.DownloadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author wxm
 * @data 2021/11/12
 */
@Service
public class DownloadServiceImpl implements DownloadService {
    /**
     *     获取日志
     */
    private final Logger logger = LoggerFactory.getLogger(DownloadServiceImpl.class);

    @Resource
    LogMapper logMapper;

    @Override
    public Boolean logDownload(String uuid, HttpServletResponse response) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        //查询后缀名
        String ext = logMapper.selectExt(uuid);
        //从数据库中查询文件路径
        String path = logMapper.selectPath(uuid) ;
        logger.info("-----info------获取文件目录成功");

        File file = new File(path);
        File file1 = new File(path +"/"+ uuid + ext);
        //判断是否没有文件
        if (!file.exists()) {
            return false;
        }
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + uuid + ext);

        byte[] buffer = new byte[1024];
        try  {
             fis = new FileInputStream(file1);
             bis = new BufferedInputStream(fis);
             os = response.getOutputStream();

            int len;
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            logger.info("-----info------文件下载成功");
            return null;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
